//
//  HWUniversal.swift
//  WoWoLiveAssistant
//
//  Created by 王昌健 on 2021/10/28.
//

import UIKit
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height

let widthScale = CGFloat(Double(String(format: "%.2f", screenWidth/375)) ?? 0)
//let widthScale = screenWidth/375
let heightScale = screenHeight/812
let scale = UIScreen.main.scale
let h = ceil(0.5 * scale) / scale
let blackTextColor = UIColor.colorWithHexString(hexString: "#333333")

var currentWindow: UIWindow? {
    if #available(iOS 13.0, *) {
        if let window = UIApplication.shared.connectedScenes
            .filter({$0.activationState == .foregroundActive})
            .map({$0 as? UIWindowScene})
            .compactMap({$0})
            .first?.windows
            .filter({$0.isKeyWindow}).first{
            return window
        }else if let window = UIApplication.shared.delegate?.window{
            return window
        }else{
            return nil
        }
    } else {
        if let window = UIApplication.shared.delegate?.window{
            return window
        }else{
            return nil
        }
    }
}
class HWUniversal: NSObject {
    
    
    func isIphone8() -> Bool {
        if screenWidth == 375 && screenHeight == 667 {
            return true
        }
        return false
    }
    func isIphone8Plus() -> Bool {
        if screenWidth == 414 && screenHeight == 736 {
            return true
        }
        return false
    }
    
}

extension HWUniversal {
    
    /// 获取当前窗口控制器
    /// - Returns: 返回控制器
    class public func getCurrentVc() -> UIViewController{
        let rootVc = currentWindow?.rootViewController
        let currentVc = getCurrentVcFrom(rootVc!)
        return currentVc
    }
    
    class private func getCurrentVcFrom(_ rootVc:UIViewController) -> UIViewController{
        var currentVc:UIViewController
        var rootCtr = rootVc
        if(rootCtr.presentedViewController != nil) {
            rootCtr = rootVc.presentedViewController!
        }
        if rootVc.isKind(of:UITabBarController.classForCoder()) {
            currentVc = getCurrentVcFrom((rootVc as! UITabBarController).selectedViewController!)
        }else if rootVc.isKind(of:UINavigationController.classForCoder()){
            currentVc = getCurrentVcFrom((rootVc as! UINavigationController).visibleViewController!)
        }else{
            currentVc = rootCtr
        }
        return currentVc
    }
    
    //View转Image
    class public func convertViewToImage(v:UIView) -> UIImage {
        //第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示透明效果，需要传false，否则传true。第三个参数就是屏幕密度了，关键就是第三个参数 UIScreen.main.scale
        UIGraphicsBeginImageContextWithOptions(v.bounds.size, false, UIScreen.main.scale)
        let ctx = UIGraphicsGetCurrentContext()!
        v.layer.render(in: ctx)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()!
        
        UIGraphicsEndImageContext()
        
        return newImage
    }
    
    
    /// 打印系统字体名
    class public func printFontName() -> Void {
        for family: String in UIFont.familyNames {
            print("\(family)")
            
            for names: String in UIFont.fontNames(forFamilyName: family) {
                print("\(names)")
            }
        }
    }
    ///字典转jsonString
    class public func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            print("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData?
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        
        
        
        return JSONString! as String
        
    }
    ///jsonString转字典
    class public func getDictionaryFromJSONString(jsonString:String) ->NSDictionary{
        
        let jsonData:Data = jsonString.data(using: .utf8)!
        
        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if dict != nil {
            return dict as! NSDictionary
        }
        return NSDictionary()
    }
    
}

extension Date {
    /// 获取当前 秒级 时间戳 - 10位
    var timeStamp : String {
        let timeInterval: TimeInterval = self.timeIntervalSince1970
        let timeStamp = Int(timeInterval)
        return "\(timeStamp)"
    }
    
    /// 获取当前 毫秒级 时间戳 - 13位
    var milliStamp : String {
        let timeInterval: TimeInterval = self.timeIntervalSince1970
        let millisecond = CLongLong(round(timeInterval*1000))
        return "\(millisecond)"
    }
}




extension HWUniversal {
    // Data转JSON字符串
    class func DataToJSONString(data: Data) -> String? {
        
        let JSONString = String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
        return JSONString
    }
    
    //Data转字典
    class func DataToDictionary(data:Data) ->Dictionary<String, Any>? {
        
        do{
            
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
            let dic = json as! Dictionary<String, Any>
            return dic
        }catch _ {
            
            return nil
        }
    }
    
    
    // JSON字符串转Data
    @objc class func JSONStringToData(json: String) -> Data? {
        
        let jsonData = json.data(using: String.Encoding.utf8, allowLossyConversion: false)
        return jsonData
    }
    
    // JSONString转换为字典
    
    class func JSONStringToDictionary(jsonString:String) ->NSDictionary{
        
        let jsonData:Data = jsonString.data(using: .utf8)!
        
        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if dict != nil {
            return dict as! NSDictionary
        }
        return NSDictionary()
    }
    
    // JSONString转换为数组
    class func JSONStringToArray(jsonString:String) ->NSArray{
        
        let jsonData:Data = jsonString.data(using: .utf8)!
        
        let array = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if array != nil {
            return array as! NSArray
        }
        return array as! NSArray
        
    }
    
    // Data转JSON(对象)
    class func DataToJSONObject(data: Data) -> Any? {
        
        do {
            return try JSONSerialization.jsonObject(with: data , options: .mutableContainers) as AnyObject
        } catch {
            print(error)
        }
        return nil
    }
    
    // JSON(对象)转Data
    class func JSONObjectToData(json: Any) -> Data? {
        
        do {
            return try JSONSerialization.data(withJSONObject: json, options: [])
        } catch {
            print(error)
        }
        return nil
    }
    
    // 字典|数组 转JSON字符串
    class func ObjectToJSONString(object: Any) -> String? {
        
        do {
            let data = try JSONSerialization.data(withJSONObject: object, options: [])
            let JSONString = String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
            return JSONString
        } catch {
            print(error)
        }
        return nil
    }
    
    class func convertDictionAryToJson(dic:NSDictionary) -> String {
        let data = try? JSONSerialization.data(withJSONObject: dic, options: JSONSerialization.WritingOptions.init(rawValue: 0))
        let jsonStr = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
        return jsonStr!
    }
    
    
    // 字典|数组 转Data
    class func ObjectToData(object: Any) -> Data? {
        
        do {
            return try JSONSerialization.data(withJSONObject: object, options: [])
        } catch {
            print(error)
        }
        return nil
        
    }
    
    class func ModelToDic(model:AnyObject)->NSDictionary{
        
        let redic = NSMutableDictionary()
        
        let mirror: Mirror = Mirror(reflecting: model)
        
        for p in mirror.children{
            
            if(p.label! != ""){
                
                redic.setValue("\(p.value)", forKey: p.label!)
                
            }
            
        }
        
        return redic
        
    }
    
    class func DicToModel(dic:Dictionary<String,String>,model:AnyObject){
        
        /// 这里将字典中所有KEY  和 值  都转换为  STRING类型，目的只有一个运用 OBJ的 setValue方法，给 这个对象赋值
        
        /// 这就完成了，字典和对象的转换
        
        let mirrotwo:Mirror = Mirror(reflecting: dic)
        
        for p in mirrotwo.children {
            
            let (key,value) = (p.value as! (String,String))
            
            //循环出字典中的每一对key - value 都是String类型，然后将这个类型赋值给model
            
            //这一次遍历当前需要赋值对象的属性，是因为需要判断当前对象是否有这个属性，如果有才会给他赋值，如果没有就略过
            
            //mirrorModel是当前需要赋值的对象的反射对象，他的LABEL就是对象的属性，value就是数值，但是只读的，
            
            //所以只能通过model.setValue来赋值
            
            let mirrorModel = Mirror(reflecting: model)
            
            for eachItem in mirrorModel.children {
                
                if(eachItem.label! == key){
                    
                    //这一步简直爆炸的方法
                    
                    model.setValue(value, forKey: key)
                    
                }
                
            }
            
        }
        
    }
}

extension NSObject {
    func getTextHeigh(textStr :  String, font : UIFont, width : CGFloat)  -> CGFloat{
        
        let normalText : NSString = textStr as NSString
        
        let size = CGSize(width: width, height:1000) //CGSizeMake(width,1000)
        
        let dic = NSDictionary(object: font, forKey : kCTFontAttributeName as! NSCopying)
        
        let stringSize = normalText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedString.Key:Any], context:nil).size
        
        return stringSize.height
        
    }
    
    //View转Image
    class public func convertCreateImageWithUIView(v:UIView) -> UIImage {
        //        UIGraphicsBeginImageContext(v.bounds.size)
        UIGraphicsBeginImageContextWithOptions(v.bounds.size, true, UIScreen.main.scale)
        let ctx = UIGraphicsGetCurrentContext()!
        v.layer.render(in: ctx)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()!
        
        UIGraphicsEndImageContext()
        
        return newImage
    }
    
    class func createQrCode(urlString:String) -> UIImage {
        /// CIFilter
        let filter = CIFilter.init(name: "CIQRCodeGenerator")
        filter?.setDefaults()
        /// Add Data
        //链接转换
        let data = urlString.data(using: .utf8)
        filter?.setValue(data, forKeyPath: "inputMessage")
        /// Out Put
        let outputImage = filter?.outputImage
        /// Show QRCode
        return createUIImageFromCIImage(image: outputImage!, size: 150)
    }
    
    class func createUIImageFromCIImage(image: CIImage, size: CGFloat) -> UIImage {
        let extent = image.extent.integral
        let scale = min(size / extent.width, size / extent.height)
        
        /// Create bitmap
        let width: size_t = size_t(extent.width * scale)
        let height: size_t = size_t(extent.height * scale)
        let cs: CGColorSpace = CGColorSpaceCreateDeviceGray()
        let bitmap: CGContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: 1)!
        
        ///
        let context = CIContext.init()
        let bitmapImage = context.createCGImage(image, from: extent)
        bitmap.interpolationQuality = .none
        bitmap.scaleBy(x: scale, y: scale)
        bitmap.draw(bitmapImage!, in: extent)
        
        let scaledImage = bitmap.makeImage()
        return UIImage.init(cgImage: scaledImage!)
    }
}
